﻿//===============================================================================
//	ServerHeartManager.h
//	服务器间心跳管理器
//===============================================================================

#include <fstream>

#include <cstdio>


#include "ServerHeartManager.h"
#include "../share/user_define.h"
#include "script_define.h"
#include "ManagerHelper.h"
#include "LuaScriptManager.h"

#include "../../3rd/libjson/json.h"

#include "../share/MessageDef.h"
#include "../share/proxyclient_service.h"
#include "../share/time_module.h"

//-------------------------------------------------------------------------------
ServerHeartManager::ServerHeartManager()
{
	m_lastMapUpdateTime = 0;
	m_lastMapHeartTime = 0;
	m_isMapStatus = false;
}

//-------------------------------------------------------------------------------
ServerHeartManager::~ServerHeartManager()
{
}

void ServerHeartManager::Initialize(void)
{
	uint64_t now = CUR_MS;
	m_lastMapUpdateTime = now;
	m_lastMapHeartTime = now;
}

//-------------------------------------------------------------------------------
void ServerHeartManager::Heartbeat(uint64_t now)
{
	_safe_guard_begin;

	if (now - m_lastMapHeartTime >= server_heart_time)
	{
		m_lastMapHeartTime = now;

		// 发送心跳请求
		Json::Value send_to_map;
		send_to_map["msgid"] = G2M_HEART_REQUEST;

		std::string m_send = JsonWriter(send_to_map);

		send_2_map(G2M_HEART_REQUEST, m_send);
	}

	// 超时 map异常
	if (m_isMapStatus && (now - m_lastMapUpdateTime >= server_heart_overtime))
	{
		m_isMapStatus = false;

		// 更新map状态
		//WebRedisMgrPtr->UpdateMapServerStatus(0);
	}

	_safe_guard_end;
}

//-------------------------------------------------------------------------------
void ServerHeartManager::UpdateG2MHeart()
{
	uint64_t now = CUR_MS;
	m_lastMapUpdateTime = now;

	if (!m_isMapStatus)
	{
		m_isMapStatus = true;

		// 更新map状态 heart中可能被误改成异常状态
		//WebRedisMgrPtr->UpdateMapServerStatus(1);
	}
	
}